<template>
  <dv-border-box-1 style="height:100%">
    <div id="border">
      <el-row :gutter="10">
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <!-- 搜索表单 -->
          <el-collapse v-model="activeName" accordion>
            <el-collapse-item title="用户查询" name="1">
              <el-form
                ref="searchForm"
                :inline="true"
                width="100%"
                :model="searchMap"
                class="demo-form-inline"
              >
                <el-form-item label="昵称" prop="username">
                  <el-input v-model="searchMap.username" placeholder="昵称"></el-input>
                </el-form-item>
                <el-form-item  label="手机" prop="mobile">
                  <el-input v-model="searchMap.mobile" placeholder="手机"></el-input>
                </el-form-item>
                <el-form-item  label="邮箱" prop="email">
                  <el-input v-model="searchMap.email" placeholder="邮箱"></el-input>
                </el-form-item>
                <el-form-item  label="性别" prop="gender">
                  <el-select v-model="searchMap.gender" clearable placeholder="请选择">
                    <el-option
                      v-for="item in genderOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                      <span style="float: left">{{ item.label }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px">{{ item.tag }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="状态" prop="isblack">
                  <el-tooltip :content="searchMap.isblack === '1' ? '正常用户' : '全部'" placement="top">
                    <el-switch
                      v-model="searchMap.isblack"
                      active-color="#13ce66"
                      inactive-color="grey"
                      active-value="1"
                      inactive-value="0"
                      @change="handleSearchBlackChange"
                    ></el-switch>
                  </el-tooltip>
                </el-form-item>
                <el-form-item label="注册时间" prop="regisdate">
                  <el-date-picker
                    v-model="searchMap.regisdate"
                    type="daterange"
                    range-separator="至"
                    value-format="yyyy-MM-dd"
                    start-placeholder="注册日期(始)"
                    end-placeholder="注册日期(至)"
                  ></el-date-picker>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="el-icon-search" @click="fetchData()">查询</el-button>
                  <el-button
                    type="primary"
                    icon="el-icon-search"
                    @click="resetSearchForm('searchForm')"
                  >置空</el-button>
                </el-form-item>
              </el-form>
            </el-collapse-item>
          </el-collapse>
          <!-- 待添加角色表单 -->
          <!-- <el-form
            v-if="!isDialog"
            :inline="true"
            width="100%"
            ref="roleaddForm"
            :rules="RulesAddRole"
            :model="pojoAddRole"
            class="demo-form-inline"
          >
            <el-form-item label="待添加角色" prop="rname">
              <el-input v-model="pojoAddRole.rname" placeholder="待添加角色名"></el-input>
            </el-form-item>
            <el-button type="primary" @click="addRole">确认添加</el-button>
            <el-button type="primary" @click="resetroleaddForm('roleaddForm')">置空</el-button>
            <el-button
              style="float:right"
              icon="el-icon-plus"
              type="primary"
              circle
              @click="handleAdd"
            ></el-button>
          </el-form> -->

          <!-- Table -->
          <el-table
            :data="list"
            style="width: 100%"
            highlight-current-row
          >
            <el-table-column  type="expand">
              <template slot-scope="props">
                <el-card shadow="hover">
                  <el-form label-position="left" inline class="demo-table-expand">
                    <el-form-item label="用户id">
                      <el-input readonly size="mini" v-model="props.row.id" placeholder="关键字"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号">
                      <el-input readonly size="mini" v-model="props.row.mobile" placeholder="关键字"></el-input>
                    </el-form-item>
                    <el-form-item label="昵称">
                      <el-input readonly size="mini" v-model="props.row.username" placeholder="关键字"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱">
                      <el-input readonly size="mini" v-model="props.row.email" placeholder="关键字"></el-input>
                    </el-form-item>

                    <el-form-item label="头像">
                      <el-avatar :src="props.row.avatar"></el-avatar>
                    </el-form-item>

                    <el-form-item label="性别">
                      <span>{{ props.row.gender == 1 ? "男" : "女" }}</span>
                    </el-form-item>
                    <el-form-item label="生日">
                      <el-date-picker
                        size="mini"
                        readonly
                        v-model="props.row.birthday"
                        type="datetime"
                        placeholder="选择日期时间"
                      ></el-date-picker>
                    </el-form-item>
                    <el-form-item label="粉丝数">
                      <span>{{ props.row.fansnum }}</span>
                    </el-form-item>
                    <el-form-item label="关注数">
                      <span>{{ props.row.follownum }}</span>
                    </el-form-item>
                    <el-form-item label="黑名单状态">
                      <el-tag :type="props.row.isblack === 1 ? 'info' : ''" effect="plain">
                        {{
                        props.row.isblack === 1 ? "已拉入黑名单" : "用户正常"
                        }}
                      </el-tag>
                    </el-form-item>
                    <el-form-item label="在线时长">
                      <span>{{ props.row.onlinetime }}</span>
                    </el-form-item>
                  </el-form>
                </el-card>
              </template>
            </el-table-column>
            <el-table-column sortable label="序号" type="index"></el-table-column>

            <el-table-column label="用户 ID" prop="id"></el-table-column>
            <el-table-column label="昵称" prop="username"></el-table-column>

            <el-table-column  label="注册日期" prop="regisdate"></el-table-column>
            <el-table-column label="最后一次登录" prop="lastlogin"></el-table-column>
            <el-table-column  sortable label="粉丝数" prop="fansnum"></el-table-column>

            <el-table-column  sortable label="积分" prop="score"></el-table-column>
            <el-table-column label="状态" prop="isblack">
              <template slot-scope="scope">
                <el-tag :type="scope.row.isblack === '1' ? 'info' : ''">
                  {{
                  scope.row.isblack === "1" ? "黑名单" : "正常"
                  }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column
             
              style="text-align:center;line-herght:100%;display:table-cell"
              label="操作"
              fixed="right"
              width="210px"
            >
              <template slot-scope="scope">
                 <el-button
                        style="float:left"
                        size="mini"
                        type="danger"
                        round
                        @click="handleBlack(scope.row.id)"
                      >拉黑</el-button>
                <el-button style="margin-left:5px" type="success" size="mini" plain>
                  <router-link
                    :to="{
                      path: '/homePage',
                      name: 'HomePage',
                      params: { userid: scope.row.id, type: 'userMsm' }
                    }"
                  >详情</router-link>
                </el-button>
                <el-button
                  style="margin-left:5px"
                  type="warning"
                  size="mini"
                  plain
                  @click="handleEdit(scope.row.id)"
                >编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </div>
    <div style="text-align:center">
      <el-button style="margin=0 auto" icon="el-icon-download" @click="loadMore">点击加载更多</el-button>
      <span style="float:right">共{{ total }}条记录</span>
    </div>
    <!-- 角色选择组件 -->
    <!-- <el-dialog title="添加角色" :visible.sync="dialogRoleVisible" width="500px">
      <role-app @option-role="optionRole" :isRoleDialog="true"></role-app>
    </el-dialog> -->
    <!-- 添加用户组件 -->
    <!-- 抽屉 -->
    <el-drawer
      title="用户编辑"
      size="50%"
      style="height:100%"
      :visible.sync="dialogUserEditVisible"
      :direction="direction"
    >
      <el-collapse v-model="activeName" style="height:100%" accordion>
       
        <el-collapse-item
          title="用户信息"
          :style="isAdd?'overflow-y:auto;height:70%':'overflow-y:auto;height:60%'"
          name="userEdit"
        >
          <el-card class="box-card" shadow="hover">
            <el-form
              ref="pojoForm"
              class="demo-form-inline"
              :model="pojo"
              :rules="RulespojoForm"
              label-position="right"
              label-width="80px"
              size="mini"
            >
              <el-form-item v-if="!isAdd" label="用户编号" prop="id">
                <el-input readonly width="60px" v-model="pojo.id" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="登录名(登录账号)" prop="loginname">
                <el-input width="60px" v-model="pojo.loginname" @blur="isInputLoginname"></el-input>
              </el-form-item>
              <el-form-item label="昵称" prop="username">
                <el-input width="60px" v-model="pojo.username"></el-input>
              </el-form-item>
     
              <el-form-item label="头像" prop="avatar">
                <el-avatar :src="pojo.avatar"></el-avatar>
              </el-form-item>
              <el-form-item label="手机号" prop="mobile">
                <el-input width="60px" v-model="pojo.mobile" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="性别" prop="gender">
                <el-select v-model="pojo.gender" clearable placeholder="请选择">
                  <el-option
                    v-for="item in genderOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                    <span style="float: left">{{ item.label }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">
                      {{
                      item.tag
                      }}
                    </span>
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="生日" prop="birthday">
                <el-date-picker
                  :readonly="!isAdd ? true : false"
                  v-model="pojo.birthday"
                  type="date"
                  placeholder="选择日期"
                ></el-date-picker>
              </el-form-item>
              <el-form-item v-if="!isAdd" label="注册日期" prop="regisdate">
                <el-date-picker readonly v-model="pojo.regisdate" type="date" placeholder="选择日期"></el-date-picker>
              </el-form-item>
              <el-form-item v-if="!isAdd" label="最后一次登录" prop="lastlogin">
                <el-date-picker readonly v-model="pojo.lastlogin" type="date" placeholder="选择日期"></el-date-picker>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input width="60px" v-model="pojo.email" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item v-if="!isAdd" label="状态" prop="isblack">
                <el-select v-model="pojo.isblack" clearable placeholder="请选择">
                  <el-option
                    v-for="item in isBlackOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                    <span style="float: left">{{ item.label }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
              <div style="float:right;margin-bottom:10px">
                <el-button @click="dialogUserEditVisible = false">取 消</el-button>

                <el-button
                  type="primary"
                  @click=" updateUser('pojoForm')"
                >修改</el-button>
              </div>
            </el-form>
          </el-card>
        </el-collapse-item>
      </el-collapse>
    </el-drawer>
  </dv-border-box-1>
</template>

<script>
import userApi from "@/api/user";
import roleApp from "@/views/user/role.vue";
import store from "../../store"
import { callbackify } from "util";
export default {
  components: {
    roleApp
  },
  props: {
    isDialog: Boolean
  },
  data() {
    /**
     * 校验密码
     */
    var validPwd = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };

    /**
     * 校验手机号
     */
    var checkMobile = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("手机号不能为空"));
      } else if (!/^1[3456789]\d{9}$/.test(value)) {
        return callback(new Error("手机号格式不正确"));
      } else {
        callback();
      }
    };
    /**
     * 校验邮箱
     */
    var checkEmail = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("邮箱不能为空"));
      } else if (
        !/^([0-9A-Za-z\-_\.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/.test(
          value
        )
      ) {
        return callback(new Error("邮箱格式不正确"));
      } else {
        callback();
      }
    };
    return {
      isinputLoginname: false, //添加用户是否输入了登录名
      fileList: [],
      disabled: false,
      dialogVisible: false, //显示放大图片
      isAdd: false, //是否为添加用户
      direction: "rtl",
      dialogUserEditVisible: false, //编辑用户窗口
      dialogRoleVisible: false, //添加角色窗口
      activeName: "",
      search: "",
      genderOptions: [
        {
          value: "1",
          label: "男",
          tag: "male"
        },
        {
          value: "0",
          label: "女",
          tag: "female"
        }
      ],
      isBlackOptions: [
        {
          value: "1",
          label: "黑名单"
        },
        {
          value: "0",
          label: "正常"
        }
      ],
     
      list: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      totalPage: 0, //总页数
      searchMap: {
        currentUserId:store.state.user.user.id,
        username: "",
        mobile: "",
        gender: "",
        isblack: "",
        regisdate: ""
      },
      checkPassword: "",
      pojo: {
        id: null,
        mobile: "",
        gender: "",
        username: "",
        email: "",
        regisdate: "",
        lastlogin: "",
        avatar: "",
        isblack: "",
        score: "",
        birthday: "",
        loginname: ""
      },
      RoleList: [], //用户的角色列表
      RulesAddRole: {
        rname: [
          { required: true, message: "待添加角色不能为空", trigger: "blur" }
        ]
      },
      RulespojoForm: {
        password: [
          { validator: validPwd, trigger: "blur" },
          {
            min: 6,
            max: 12,
            message: "密码长度在 6 到 12 个字符",
            trigger: "blur"
          }
        ],

        mobile: [
          //  { required: true, message: "手机号不能为空", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ],
        gender: [
          { required: true, message: "请选择您的性别", trigger: "blur" }
        ],
        loginname: [
          { required: true, message: "登录账号不能为空", trigger: "blur" },
          {
            min: 4,
            max: 20,
            message: "登录账号长度在 4 到 20 个字符",
            trigger: "blur"
          }
        ],
        username: [
          { required: true, message: "昵称不能为空", trigger: "blur" },
          {
            min: 4,
            max: 15,
            message: "昵称长度在 4 到 15 个字符",
            trigger: "blur"
          }
        ],
        birthday: [
          {
            required: true,
            message:
              "请填写您的生日，以便小W为您送上生日祝福(生日信息会严格保存)",
            trigger: "blur"
          }
        ],
        email: [
          // { required: true, message: "请输入邮箱地址", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ]
      }
    };
  },
  // watch: {
  //   "pojo.avatar"(newValue, oldValue) {
  //     if (!newValue) {
  //       this.isUpload = true;
  //     }
  //   }
  // },
  // created() {
  //   this.fetchData();
  // },
  mounted() {
    this.fetchData();
  },
  methods: {
    /**
     * 判断是否输入登录名
     */
    isInputLoginname() {
      if (this.pojo.loginname === "") {
        this.isinputLoginname = false;
      } else {
        this.isinputLoginname = true;
      }
    },
   

    fetchData() {
      userApi
        .searchPage(this.currentPage, this.pageSize, this.searchMap)
        .then(resp => {
          const respData = resp.data;
          if (respData.flag) {
            this.list = respData.data.rows;
            this.total = respData.data.total;
            this.totalPage =
              this.total / this.pageSize <=1
                ? 1
                : Math.ceil(this.total / this.pageSize);//Math.ceil向上取整
           // console.log(this.list);
            //consoleconsole.log(this.totalPage)
          } else {
            this.$message({
              message: respData.message,
              type: "warning"
            });
          }
        });
    },
    /**
     * 打开添加用户窗口
     */
    handleAdd() {
      this.isAdd = true;
      this.dialogUserEditVisible = true;
      this.$nextTick(() => {
        this.$refs["pojoForm"].resetFields();
        this.checkPassword = "";
      });
      this.pojo.id=null
    },
    /**
     * 添加用户
     */
    addUser() {
      //console.log(this.$refs.pojoForm)
      this.$refs.pojoForm.validate(valid => {
        if (valid) {
          if (this.pojo.avatar !== ""&&this.pojo.avatar!==null) {
            userApi.addUser(this.pojo).then(resp => {
              if (resp.data.flag) {
                this.$message({
                  type: "success",
                  message: resp.data.message
                });
                this.dialogUserEditVisible = false;
                this.fetchData()
              }else{
                 this.$message({
                  type: "warning",
                  message: resp.data.message
                });
               
              }
            });
          } else {
            this.$message({
              message: "请先上传头像",
              type: "warning"
            });
          }
        } else {
          this.$message({
            message: "请检查格式是否正确",
            type: "warning"
          });
        }
      });
    },
    /**
     * 打开编辑窗口
     */
    handleEdit(id) {
      this.handleAdd();
      this.isAdd = false;
      userApi.getById(id).then(resp => {
        const respData = resp.data;
        if (respData.flag) {
          this.pojo = respData.data;
        } else {
          this.$message({
            type: "warning",
            message: respData.message
          });
        }
      });
    //  this.getRoleListById(id);
    },
    /**
     * 查询角色列表
     */
    getRoleListById(userid) {
      userApi.getRoleListById(userid).then(respRole => {
        const respRoleData = respRole.data;
        if (respRoleData.flag) {
          this.RoleList = respRoleData.data;
        } else {
          this.$message({
            type: "warning",
            message: respRoleData.message
          });
        }
      });
    },
    /**
     * 根据用户id删除角色
     */
    handleDeleteRole(rid) {
      this.$confirm("确定删除此角色吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          userApi.deleteRoleById(this.pojo.id, rid).then(resp => {
            if (resp.data.flag) {
              this.$message({
                type: "success",
                message: resp.data.message
              });
              this.getRoleListById(this.pojo.id);
            } 
          });
        })
        .catch(() => {
          return;
        });
    },
    /**
     * 修改用户信息
     */
    updateUser() {
      this.$refs.pojoForm.validate(valid => {
        if (valid) {
          userApi.update(this.pojo).then(resp => {
            if (resp.data.flag) {
              this.$message({
                type: "success",
                message: resp.data.message
              });
              this.fetchData()
              this.dialogUserEditVisible = false;
            } else {
              this.$message({
                type: "warning",
                message: resp.data.message
              });
            }
          });
        } else {
          this.$message({
            type: "warning",
            message: "请检查填写的信息格式"
          });
        }
      });
    },
    
   
   
    /**
     * 查询表单置空
     */
    resetSearchForm(formName) {
      this.$refs[formName].resetFields();
    },
    /**
     * 拉黑
     */
    handleBlack(id) {
      this.$confirm("确定拉黑此用户吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          userApi.blackUser(id).then(resp => {
            this.$message({
              type: resp.data.flag ? "success" : "error",
              message: resp.data.message
            });
            if (resp.data.flag) {
              this.fetchData();
            }
          });
        })
        .catch(() => {
          return;
        });
    },
    /**
     * 查询表单的性别
     */
    handleSearchGenderChange(val) {
      this.searchMap.gender = val;
    },
    /**
     * 查询表单的黑名单条件
     */
    handleSearchBlackChange(val) {
      this.searchMap.isblack = val;
    },
    /**
     * 加载更多
     */
    loadMore() {
      if (this.currentPage < this.totalPage) {
        //没有到最后一页
        this.currentPage++;
        userApi
          .searchPage(this.currentPage, this.pageSize, this.searchMap)
          .then(resp => {
            const respData = resp.data;
            if (respData.flag) {
              this.list = this.list.concat(respData.data.rows);
            } else {
              this.$message({
                message: respData.message,
                type: "warning"
              });
            }
          });
      }else{
        this.$message({
          type:'info',
          message:"已经全部加载完啦"
        })
      }
    },

    handleAvatarSuccess(res, file) {
      this.pojo.avatar = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    }
  }
};
</script>
<style scoped>
#border {
  padding: 20px;
}
/*table  css */
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
  margin-right: 10px;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
/* 头像上传 */
.avatar-uploader .el-upload {
  border: 1px dashed #c22cd6;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #0e76df;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
}
.avatar {
  width: 80px;
  height: 80px;
  display: block;
  border: 1px dashed #c22cd6;
}
</style>
